var listButton = document.getElementsByClassName("bottom-icon list")[0];
var musicList = document.getElementsByClassName("music-list")[0];
var closeList = document.getElementsByClassName("close-list")[0];
var audio = document.getElementById("audioTag");
var recordImg = document.getElementsByClassName("rotate-play")[0];
var progress = document.getElementsByClassName("pgs-play")[0];
var pause = document.getElementsByClassName("icon-play")[0];
var progressTotal = document.getElementsByClassName("pgs-total")[0];
var playedTime = document.getElementsByClassName("played-time")[0];
var totalTime = document.getElementsByClassName("audio-time")[0];
var volumnButton = document.getElementsByClassName("volumn")[0];
var volumnTogger = document.getElementById("volumn-togger");

// 获取上一首和下一首按钮
var skipForward = document.getElementsByClassName("s-left")[0];
console.log("MV Button element:", mvButton);
var skipBackward = document.getElementsByClassName("s-right")[0];

// 获取MV按钮
var mvButton = document.getElementsByClassName("bottom-icon MV")[0];

// 获取倍速显示元素
var speedButton = document.getElementsByClassName("speed")[0];

// 获取歌曲名称和作者的显示元素
var musicTitleDisplay = document.getElementsByClassName("music-title")[0];
var authorNameDisplay = document.getElementsByClassName("author-name")[0];

// 音乐数据（文件名、标题、作者）
var musicData = ["music0.mp3", "music1.mp3", "music2.mp3", "music3.mp3"];
var musicTitles = ["洛春赋", "Yesterday", "江南烟雨色", "Vision"];
var musicAuthors = ["银临", "The Beatles", "司南", "Gareth Emery"]; // 假设的作者



var mvData = ["music0.mp4", "music1.mp4",  "music2.mp4", "music3.mp4"]; 

// 获取所有播放列表中的歌曲项
var musicItems = document.querySelectorAll(".all-list div");


// 音乐播放列表显示
listButton.addEventListener("click", function () {
  musicList.classList.remove("list-card-hide");
  musicList.classList.add("list-card-show");
  musicList.style.display = "block";
  closeList.style.display = "block";
});

// 音乐播放列表隐藏
closeList.addEventListener("click", function () {
  musicList.classList.remove("list-card-show");
  musicList.classList.add("list-card-hide");
  closeList.style.display = "none";
});

// 初始化音乐（加载歌曲并更新信息）
var musicId = 0;
function initMusic() {
  audio.src = "mp3/" + musicData[musicId];
  audio.load();

  musicTitleDisplay.innerText = musicTitles[musicId];
  authorNameDisplay.innerText = musicAuthors[musicId];

  updatePlaylistHighlight();

  audio.onloadedmetadata = function () {
    totalTime.innerText = transTime(audio.duration);
  };

  audio.onended = function () {
    musicId = (musicId + 1) % musicData.length;
    initAndPlay();
  };

  // 重置倍速到默认值 1.0X
  audio.playbackRate = 1.0;
  speedButton.innerText = "1.00X";
  currentSpeedIndex = 0;
}
initMusic();


// 播放音乐并开始唱片旋转
function initAndPlay() {
  initMusic(); // 重新初始化（会加载新歌曲和更新信息）
  audio.play();
  pause.classList.remove("icon-play");
  pause.classList.add("icon-pause");
  rotateRecord();
}

// 唱片旋转函数
function rotateRecord() {
  recordImg.style.animationPlayState = "running";
}

// 停止旋转函数
function rotateRecordStop() {
  recordImg.style.animationPlayState = "paused";
}

// 暂停播放按钮的事件监听
pause.addEventListener("click", function () {
  if (audio.paused) {
    audio.play();
    pause.classList.remove("icon-play");
    pause.classList.add("icon-pause");
    rotateRecord();
  } else {
    audio.pause();
    pause.classList.remove("icon-pause");
    pause.classList.add("icon-play");
    rotateRecordStop();
  }
});

// 更新进度条
audio.addEventListener("timeupdate", updateProgress);
function updateProgress() {
  var value = audio.currentTime / audio.duration;
  progress.style.width = value * 100 + "%";
  playedTime.innerText = transTime(audio.currentTime);
}

// 点击进度条跳转播放
progressTotal.addEventListener("click", function (event) {
  if (!isNaN(audio.duration) && isFinite(audio.duration)) {
    // 检查 duration 是否有效
    var pgsWidth = progressTotal.offsetWidth;
    var rate = event.offsetX / pgsWidth;
    audio.currentTime = rate * audio.duration;
    updateProgress();
  }
});

// 音频播放时间换算
function transTime(value) {
  if (isNaN(value) || !isFinite(value)) {
    return "00:00"; // 如果值无效，返回默认
  }
  var time = "";
  var h = parseInt(value / 3600);
  value %= 3600;
  var m = parseInt(value / 60);
  var s = parseInt(value % 60);
  if (h > 0) {
    time = formatTime(h + ":" + m + ":" + s);
  } else {
    time = formatTime(m + ":" + s);
  }
  return time;
}

// 格式化时间显示，补零对齐
function formatTime(value) {
  var time = "";
  var s = value.split(":");
  var i = 0;
  for (; i < s.length - 1; i++) {
    time += s[i].length == 1 ? "0" + s[i] : s[i];
    time += ":";
  }
  time += s[i].length == 1 ? "0" + s[i] : s[i];
  return time;
}

// 音量控制
var lastVolume = 70;
audio.volume = lastVolume / 100;

// 拖动音量条实时更新音量
volumnTogger.addEventListener("input", function () {
  audio.volume = volumnTogger.value / 100;
  if (audio.volume > 0) {
    lastVolume = volumnTogger.value; // 只有在音量大于0时才更新lastVolume
    volumnButton.style.backgroundImage = "url(./img/音量.png)";
    audio.muted = false; // 解除静音
  } else {
    volumnButton.style.backgroundImage = "url(./img/静音.png)";
    audio.muted = true; // 静音
  }
});

// 点击静音按钮
function setVoulumn() {
  audio.muted = !audio.muted;
  if (audio.muted) {
    lastVolume = volumnTogger.value; // 静音前保存当前音量
    volumnTogger.value = 0;
    volumnButton.style.backgroundImage = "url(./img/静音.png)";
  } else {
    volumnTogger.value = lastVolume; // 恢复上次的音量
    audio.volume = lastVolume / 100; // 实际设置音量
    volumnButton.style.backgroundImage = "url(./img/音量.png)";
  }
}
volumnButton.addEventListener("click", setVoulumn);

// 上一首
skipForward.addEventListener("click", function () {
  musicId = musicId - 1;
  if (musicId < 0) {
    musicId = musicData.length - 1; // 循环到列表的最后一首
  }
  initAndPlay();
});

// 下一首
skipBackward.addEventListener("click", function () {
  musicId = musicId + 1;
  if (musicId >= musicData.length) {
    // 检查是否超出数组长度
    musicId = 0; // 循环到列表的第一首
  }
  initAndPlay();
});

// 更新播放列表高亮状态
function updatePlaylistHighlight() {
  musicItems.forEach((item, index) => {
    if (index === musicId) {
      item.style.color = "lightgreen"; // 高亮当前播放歌曲
      item.style.fontWeight = "bold";
    } else {
      item.style.color = "white"; // 其他歌曲恢复默认颜色
      item.style.fontWeight = "300";
    }
  });
}

// 给播放列表中的歌曲添加点击事件
musicItems.forEach((item, index) => {
  item.addEventListener("click", function () {
    musicId = index; // 设置当前歌曲ID为点击的歌曲
    initAndPlay(); // 播放点击的歌曲
    // 播放列表点击后可以自动关闭 (可选)
    // musicList.classList.remove("list-card-show");
    // musicList.classList.add("list-card-hide");
    // closeList.style.display = "none";
  });
});

// 定义倍速选项数组和当前倍速的索引
var playbackSpeeds = [1.0, 1.25, 1.5, 2.0, 0.75, 0.5]; // 更多的倍速选项
var currentSpeedIndex = 0; // 初始倍速为 1.0 (数组的第一个元素)

// 倍速按钮点击事件
speedButton.addEventListener("click", function () {
  // 切换到下一个倍速
  currentSpeedIndex = (currentSpeedIndex + 1) % playbackSpeeds.length;
  var newSpeed = playbackSpeeds[currentSpeedIndex];

  // 应用新的倍速到音频标签
  audio.playbackRate = newSpeed;

  // 如果MV正在播放，也应用到MV视频标签
  if (mvPlayerOverlay.style.display === "flex") {
    mvVideo.playbackRate = newSpeed;
  }

  // 更新倍速显示文本，保留两位小数
  speedButton.innerText = newSpeed.toFixed(2) + "X";
});

// MV按钮点击事件 (修改为页面跳转)
mvButton.addEventListener("click", function () {
  console.log("MV Button clicked!"); // 添加这行
  var currentMvPath = mvData[musicId]; // 获取当前歌曲对应的MV路径

  if (currentMvPath) {
    // 如果有MV
    audio.pause(); // 暂停音频播放
    // 传递当前歌曲ID和当前倍速到MV播放页面
    window.location.href = `mv_player.html?musicId=${musicId}&speed=${audio.playbackRate}`;
  } else {
    // 如果当前歌曲没有MV，给出提示
    alert("当前歌曲没有MV。");
  }
});

// 倍速按钮点击事件
speedButton.addEventListener("click", function () {
  currentSpeedIndex = (currentSpeedIndex + 1) % playbackSpeeds.length;
  var newSpeed = playbackSpeeds[currentSpeedIndex];

  audio.playbackRate = newSpeed; // 应用到音频播放器

  // 更新倍速显示文本
  speedButton.innerText = newSpeed.toFixed(2) + "X";
});
